﻿using Admin.ApplicationLib.Entities;
using Admin.ApplicationLib.Repositories;
using Admin.ApplicationLib.Specifications;
using Admin.CommonLib.Models.Organization;
using AutoMapper;
using Swimj.CommonLib.Base;

namespace Admin.ApplicationLib.Services
{
    public class OrganizationService : IOrganizationService
    {
        private readonly IOrganizationRepository _organizationRepository;
        private readonly IMapper _mapper;

        public OrganizationService(IOrganizationRepository organizationRepository,
            IMapper mapper)
        {
            _organizationRepository = organizationRepository;
            _mapper = mapper;
        }

        public async Task<Result<IList<OrganizationInfoResponseDto>>> QueryOrganizationsAsync(
            OrganizationSearchRequestDto model)
        {
            var organizationSpecification = new OrganizationSpecification(model);

            var organizationEntities = await _organizationRepository.ListAsync(organizationSpecification);

            return await Result<IList<OrganizationInfoResponseDto>>.SuccessAsync(
                _mapper.Map<IList<OrganizationInfoResponseDto>>(organizationEntities));
        }

        public async Task<PaginatedResult<OrganizationInfoResponseDto>> QueryOrganizationsByPageAsync(
            OrganizationSearchRequestDto model)
        {
            var organizationSpecification = new OrganizationSpecification(model);

            var organizationEntities = await _organizationRepository.ListAsync(organizationSpecification);

            var count = await _organizationRepository.CountAsync(organizationSpecification);
            return await PaginatedResult<OrganizationInfoResponseDto>.SuccessAsync(
                _mapper.Map<List<OrganizationInfoResponseDto>>(organizationEntities), count,
                model.Page, model.Limit);
        }

        public async Task<Result<OrganizationInfoResponseDto>> CreateOrganization(OrganizationEditRequestDto model)
        {
            var organizationEntity = _mapper.Map<OrganizationEntity>(model);

            organizationEntity = await _organizationRepository.AddAsync(organizationEntity);
            return await Result<OrganizationInfoResponseDto>.SuccessAsync(
                _mapper.Map<OrganizationInfoResponseDto>(organizationEntity));
        }
    }
}